import { findProjectDict,
  findGameProject,
  addGameProject,
  removeGameProject, } from '../services/gameProject';

export default {
  namespace: 'gameProject',

  state: {
    selectedProectDictList: [],
    projectDictList: [],
    projectDictMap: {},
    gameProjectList: [],
    gameProjectZubie: {},
  },

  effects: {
    *findProjectDict({ payload }, { select, call, put }) {
      const response = yield call(findProjectDict, payload);
      //console.log(response)
      if (response) {
        const projectDictMap = {};
        response.forEach(element => {
          projectDictMap[element.code] = element;
        });

        yield put({
          type: 'changeState',
          payload: {
            projectDictList: Array.isArray(response) ? response : [],
            projectDictMap,
          },
        });
      }
    },
    *addGameProject({ payload }, { select, call, put }) {
      const curGame = yield select(state => state.gameList.modifyItem);
      payload.gameCode = curGame.code;
      payload.status = 'N';
      yield call(addGameProject, payload);
      yield put({
        type: 'findGameProject',
      });
    },
    *removeGameProject({ payload }, { select, call, put }) {
      const curGame = yield select(state => state.gameList.modifyItem);
      payload.gameCode = curGame.code;
      yield call(removeGameProject, payload);
      yield put({
        type: 'findGameProject',
      });
    },
    *findGameProject(_, { select, call, put }) {
      const curGame = yield select(state => state.gameList.modifyItem);
      const response = yield call(findGameProject, curGame.code);
      if (response) {
        yield put({
          type: 'changeState',
          payload: {
            gameProjectList: response.listData,
            gameProjectZubie: response.mapData,
          },
        });
      }
    },
  },

  reducers: {
    changeState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
